package com.limh.keepalive.core

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.limh.keepalive.R
import java.lang.ref.WeakReference
import java.lang.reflect.ParameterizedType

/**
 * @author limh
 * @function
 * @date 2021/4/19 18:02
 */
abstract class BaseActivity<T : ViewBinding> : AppCompatActivity(), HandlerAction, KeyboardAction {

    val TAG = javaClass.simpleName
    lateinit var context: Context
    lateinit var binding: T

    private var isFirstRun = true
    var isResume = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLayout()
        context = WeakReference(this).get()!!
        initViews()
    }

    override fun onResume() {
        super.onResume()
        if (isFirstRun || isResume) {
            initDatas()
        }
        isFirstRun = false
    }

    override fun startActivityForResult(intent: Intent?, requestCode: Int, options: Bundle?) {
        // 隐藏软键，避免内存泄漏
        hideKeyboard(currentFocus)
        // 查看源码得知 startActivity 最终也会调用 startActivityForResult
        super.startActivityForResult(intent, requestCode, options)
    }

    override fun finish() {
        // 隐藏软键，避免内存泄漏
        hideKeyboard(currentFocus)
        super.finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        removeCallbacks()
    }

    private fun setLayout() {
        val type = javaClass.genericSuperclass as ParameterizedType
        val cls: Class<*> = type.actualTypeArguments[0] as Class<*>
        try {
            val inflate = cls.getDeclaredMethod("inflate", LayoutInflater::class.java)
            binding = inflate.invoke(null, layoutInflater) as T
            setContentView(binding.root)
            initSoftKeyboard()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 初始化软键盘
     */
    protected open fun initSoftKeyboard() {
        // 点击外部隐藏软键盘，提升用户体验
        getContentView().setOnClickListener { v: View? ->
            // 隐藏软键，避免内存泄漏
            hideKeyboard(currentFocus)
        }
    }

    abstract fun initViews()
    abstract fun initDatas()

    inline fun <reified T> startActivity(context: Context) {
        val intent = Intent(context, T::class.java)
        context.startActivity(intent)
    }

    inline fun <reified T> startActivity(context: Context, block: Intent.() -> Unit) {
        val intent = Intent(context, T::class.java)
        intent.block()
        context.startActivity(intent)
    }

    open fun getContentView(): ViewGroup {
        return findViewById(Window.ID_ANDROID_CONTENT)
    }
}